﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace I_SheepManagement.Infrastructure
{
    public class BaseRepository<T> : IRepository<T> where T : class
    {
        private readonly MyDbContext _dbContext;

        public BaseRepository(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<int> AddAsync(T entity)
        {
            await _dbContext.Set<T>().AddAsync(entity);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await _dbContext.Set<T>().ToListAsync();
        }

        public async Task<T> GetByFuncAsync(Expression<Func<T, bool>> handler)
        {
            return await _dbContext.Set<T>().Where(handler).FirstOrDefaultAsync();
        }

        public async Task<List<T>> GetByFuncListAsync(Expression<Func<T, bool>> handler)
        {
            return await _dbContext.Set<T>().Where(handler).ToListAsync();
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }

        public async Task<int> UpdateAsync(T entity)
        {
            _dbContext.Set<T>().Update(entity);
            return await _dbContext.SaveChangesAsync();
        }
    }
}
